<?php

namespace app\cps\service;

use app\model\Link;
use app\model\ThirdVideos;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Session;
use app\model\OfficialAccounts;
use app\model\Applet;
use app\model\Videos;
use app\model\VideoDetails;
use app\model\EchoRuleConfig;
use app\model\RechargeTemplate;
use app\model\User;
use app\model\PayRecord;
use app\model\CollectionLink;
use think\facade\Db;
use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\DailyDeliveryData;
use app\model\ResponsibilityPerson;
use app\model\VideoPayConfig;
use app\model\RechargeLimitTemplateVideo;
use app\model\RechargeLimitTemplateCompany;
use think\facade\Log;
use app\model\CustomRechargeTemplate;

/**
 * 链接服务
 */
class LinkService
{
    private $model;
    private $officialAccountsModel;
    private $appletModel;
    private $videosModel;
    private $detailModel;
    private $echoRuleConfigModel;
    private $rechargeTemplateModel;
    private $userModel;
    private $payRecordModel;
    private $collectionLinkModel;
    private $dailyDeliveryDataModel;
    private $responsibilityPersonModel;
    private $videoPayConfigModel;
    private $rechargeLimitTemplateVideo;
    private $rechargeLimitTemplateCompany;
    private $customRechargeTemplateModel;

    public function __construct(Link $model, OfficialAccounts $officialAccountsModel, Applet $appletModel, Videos $videosModel, VideoDetails $detailModel, EchoRuleConfig $echoRuleConfigModel, RechargeTemplate $rechargeTemplateModel, User $userModel, PayRecord $payRecordModel, CollectionLink $collectionLinkModel, DailyDeliveryData $dailyDeliveryDataModel, ResponsibilityPerson $responsibilityPersonModel, VideoPayConfig $videoPayConfigModel, RechargeLimitTemplateVideo $rechargeLimitTemplateVideo, RechargeLimitTemplateCompany $rechargeLimitTemplateCompany, CustomRechargeTemplate $customRechargeTemplateModel)
    {
        $this->model = $model;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->appletModel = $appletModel;
        $this->videosModel = $videosModel;
        $this->detailModel = $detailModel;
        $this->echoRuleConfigModel = $echoRuleConfigModel;
        $this->rechargeTemplateModel = $rechargeTemplateModel;
        $this->userModel = $userModel;
        $this->payRecordModel = $payRecordModel;
        $this->collectionLinkModel = $collectionLinkModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->videoPayConfigModel = $videoPayConfigModel;
        $this->rechargeLimitTemplateVideo = $rechargeLimitTemplateVideo;
        $this->rechargeLimitTemplateCompany = $rechargeLimitTemplateCompany;
        $this->customRechargeTemplateModel = $customRechargeTemplateModel;
    }

    // 添加推广链接
    public function editLink($params, $userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        $appletId = $this->officialAccountsModel->getInfoById($usedOfficialAccountId, 'applet_id')['applet_id'];
        $cpsId = $userInfo['cps_user_id'];
        $videoId = $params['video_id'];

        $appletData = $this->appletModel->getInfoById($appletId, 'url, app_id, app_secret');

        if (empty($appletData['url'])) {
            return ['message' => Error::APPLET_URL_NOT_EXIXTS];
        }

        $videoData = $this->videosModel->getInfoById($videoId, 'launch_start_time');

        if (empty($videoData)) {
            return ['message' => '获取视频信息失败'];
        }

        $responsibilityPerson = $this->responsibilityPersonModel->getInfoById($cpsId, 'pid,is_distributor,company_id');
        if (!empty($responsibilityPerson['pid']) && !empty($responsibilityPerson['is_distributor'])) {

            if (empty($params['advertiser_id'])) {
                return ['message' => Error::ADVERTISER_ID_NOT_EXIXTS];
            }
            if (empty($params['rebate'])) {
                return ['message' => Error::REBATE_NOT_EXISTS];
            }
        }

        // 新版自定义充值配置
        $params['is_new_recharge_setting'] = 2;
        // 新版回传设置
        $params['is_new_back_setting'] = 2;
        // if (!empty($params['id'])) {
        //     $linkInfo = $this->model->getInfoByWhere(['id' => $params['id']], 'is_new_recharge_setting, is_new_back_setting');
        //     if ($linkInfo['is_new_recharge_setting'] == 1) {
        //         $params['is_new_recharge_setting'] = 1;
        //     }
        //     if ($linkInfo['is_new_back_setting'] == 1) {
        //         $params['is_new_back_setting'] = 1;
        //     }
        // }

        $rechargeLimitTemplateData = $this->rechargeLimitTemplateVideo->selectWithTemplateFirstByVideoId(['recharge_limit_template_id'], $videoId);

        // 新剧三天内开始投放的，判断使用充值模板不能低于9.9和收费起始集数不得超过第20集
        // 查询短剧的开始投放时间
        if (!empty($rechargeLimitTemplateData)) {
            $companyId = $responsibilityPerson['company_id'];
            $rechargeLimitTemplateId = $rechargeLimitTemplateData['recharge_limit_template_id'];

            $rechargeLimitCompanyData = $this->rechargeLimitTemplateCompany->selectFirstByRechargeLimitTemplateIdAndCompanyId(['company_id'], $rechargeLimitTemplateId, $companyId);
            if (empty($rechargeLimitCompanyData)) {
                if ($videoData['launch_start_time'] > time() - ($rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_day'] * 86400)) {
                    if (!empty($params['recharge_template_id'])) {

                        $rechargeTemplateData = $this->customRechargeTemplateModel->getInfoById($params['recharge_template_id'], 'recharged_content, not_recharged_content, sort');

                        if ($rechargeTemplateData['sort'] > $rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_set']) {
                            return ['message' => Error::PAYMENT_START_COLLECTION_EXCEED . '第' . $rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_set'] . '集'];
                        }
                        $rechargedContent = json_decode($rechargeTemplateData['recharged_content'], true);
                        $notRechargedContent = json_decode($rechargeTemplateData['not_recharged_content'], true);

                        if (!empty($rechargedContent) && is_array($rechargedContent)) {
                            foreach ($rechargedContent as $item) {
                                if ($item['recharge_price'] < $rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_amount']) {
                                    return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT . '（' . $rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_amount'] . '）'];
                                }
                            }
                        }

                        if (!empty($notRechargedContent) && is_array($notRechargedContent)) {
                            foreach ($notRechargedContent as $item) {
                                if ($item['recharge_price'] < $rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_amount']) {
                                    return ['message' => Error::PAYMENT_AMOUNT_NOT_LESS_THAN_DESIGNATED_AMOUNT . '（' . $rechargeLimitTemplateData['rechargeLimitTemplate']['recharge_amount'] . '）'];
                                }
                            }
                        }
                    }
                }
            }
        }

        // by huangxiaoshan add 2023-07-17 登录用户身份判断
        $userIdentityRow = $this->responsibilityPersonModel->getInfoById($cpsId, 'pid, is_distributor');

        $userIsDistributor = false; // 登录用户不是分销商
        if ($userIdentityRow['pid'] > 0) {
            $distributorData = $this->responsibilityPersonModel->getInfoById($userIdentityRow['pid'], 'is_distributor');
            if (!empty($distributorData['is_distributor'])) {
                $userIsDistributor = true;
            }
        }
        // end

        $params['url'] = $appletData['url'] . '?video_id=' . $params['video_id'] . '&video_detail_id=' . $params['video_detail_id'];

        $linkUrl = [];
        Db::startTrans();
        try {
            if (empty($params['id'])) {
                $create_link_count = 1;
                // 批量创建链接
                if ($userIsDistributor) { // 分销商下面的投手。
                    $create_link_count = $params['link_count'] ?? 1;
                }

                // 分销金额的创建开始
                $designatedAmountEcho = [];
                if (!empty($params['designated_amount_echo'])) {
                    $designatedAmountEcho = json_decode($params['designated_amount_echo'], true);
                }

                // 指定金额回传
                if (!empty($params['design_switch']) && !empty($designatedAmountEcho[0]['price'])) {

                    $amountEcho = $price = [];
                    $time = time();
                    foreach ($designatedAmountEcho as $value) {
                        // 回传金额和回传率需同事存在
                        if (empty($value['price']) || empty($value['rate'])) {
                            return ['code' => Error::FAIL_CODE, 'message' => Error::AMOUNT_OR_RETURN_RATE_CANNOT_BE_EMPTY];
                        }

                        // 判断是否存在填写一样的金额一样的数据
                        if (in_array($value['price'], $price)) {
                            return ['code' => Error::FAIL_CODE, 'message' => Error::THERE_IS_DATA_WITH_THE_SAME_AMOUNT];
                        }
                        $price[] = $value['price'];
                        $amountEcho[] = ['price' => $value['price'], 'rate' => $value['rate'], 'update_time' => $time];
                    }
                    $params['designated_amount_echo'] = json_encode($amountEcho);
                } else {
                    unset($params['designated_amount_echo']);
                }
                // 结束

                if ($userIsDistributor) { // 分销商下面的投手。
                    for ($i = 0; $i < $create_link_count; $i++) { // 根据自定义的创建数量进行批量创建
                        unset($params['link_count']);
                        $linkUrl[] = $this->saveLIink($usedOfficialAccountId, $cpsId, $params);// 不能一次性保存。所以返回结果没意义
                    }
                } else { // 非分销商的话。默认根据提交过来的广告进行批量创建。
                    $advertiserIdArray = explode(',', $params['advertiser_id']); // 格式是：广告ID，广告ID，广告ID。分割数组
                    foreach ($advertiserIdArray as $key => $val) { // 批量提交过来的数据先进行校验能不能进行saveLIink进行。
                        if (!$val) {
                            return ['message' => '广告ID' . $val . ':' . Error::ADVERTISER_ID_NOT_EXIXTS];
                        }
                        if (!empty($params['link_switch'])) {
                            if (!empty($val)) {
                                $isExistsData = Db::name('link')->where(['advertiser_id' => $val, 'link_switch' => 1])->find();
                                if ($isExistsData) {
                                    return ['message' => "广告ID" . $val . ":" . Error::ADVERTISER_ID_ALREADY_OCCUPIED];
                                }
                            }
                        }
                    }

                    // 按广告ID进行创建.
                    foreach ($advertiserIdArray as $key => $val) {
                        $params['advertiser_id'] = $val; // 单个
                        unset($params['link_count']);
                        $linkUrl[] =  $this->saveLIink($usedOfficialAccountId, $cpsId, $params);
                    }
                }

            } else {
                // 除当前链接使用该广告账户外是否还有其他链接使用
                if (!empty($params['link_switch'])) {
                    if (!empty($params['advertiser_id'])) {
                        $isExistsData = Db::name('link')->where([['advertiser_id', '=', $params['advertiser_id']], ['link_switch', '=', 1], ['id', '<>', $params['id']]])->find();
                        if ($isExistsData) {
                            return ['message' => Error::ADVERTISER_ID_ALREADY_OCCUPIED];
                        }
                    }
                }

                $params['updated_at'] = time();
                unset($params['link_count']);
                // 获取链接数据
                $linkData = Db::name('link')->where(['id' => $params['id']])->field('echo_rate, link_switch')->find();
                if ($linkData['link_switch'] == 0 && $params['link_switch'] == 1) {
                    $params['release_start_time'] = time();
                    $params['release_end_time'] = null;
                }
                if ($linkData['link_switch'] == 1 && $params['link_switch'] == 0) {
                    $params['release_end_time'] = time();
                }

                // if ($linkData['echo_rate'] != $params['echo_rate']) {
                //     // 修改回传率修改时间
                //     $params['edit_echo_rate_time'] = time();
                // }

                $designatedAmountEcho = [];
                if (!empty($params['designated_amount_echo'])) {
                    $designatedAmountEcho = json_decode($params['designated_amount_echo'], true);
                }

                // 指定金额回传
                if (!empty($params['design_switch']) && !empty($designatedAmountEcho[0]['price'])) {

                    $amountEcho = $price = [];
                    // $time = time();
                    foreach ($designatedAmountEcho as $value) {
                        // 回传金额和回传率需同事存在
                        if (empty($value['price']) || empty($value['rate'])) {
                            return ['code' => Error::FAIL_CODE, 'message' => Error::AMOUNT_OR_RETURN_RATE_CANNOT_BE_EMPTY];
                        }

                        // 判断是否存在填写一样的金额
                        if (in_array($value['price'], $price)) {
                            return ['code' => Error::FAIL_CODE, 'message' => Error::THERE_IS_DATA_WITH_THE_SAME_AMOUNT];
                        }
                        $price[] = $value['price'];
                        $amountEcho[] = ['price' => $value['price'], 'rate' => $value['rate'], 'update_time' => $value['update_time']];
                    }
                    $params['designated_amount_echo'] = json_encode($amountEcho);
                } else {
                    unset($params['designated_amount_echo']);
                }

                Db::name('link')->save($params);
            }

            // 提交事务
            Db::commit();
            return $linkUrl;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['message' => $e->getMessage()];
        }
    }

    // 保存推广链接 by huangxiaoshan 2023-07-17
    public function saveLIink($usedOfficialAccountId, $cpsId, $params = [])
    {
        // 添加
        if (!empty($params['link_switch'])) { // 投放开关打开.
            $params['release_start_time'] = time();
        }

        $params['official_account_id'] = $usedOfficialAccountId;
        $params['responsibility_person_id'] = $cpsId;

        // 获取公众号
        $officialAccountsData = $this->officialAccountsModel->getInfoById($usedOfficialAccountId, 'applet_id');
        $appletData = $this->appletModel->getInfoById($officialAccountsData['applet_id'], 'type');
        $params['link_type'] = $appletData['type'];

        $params['created_at'] = time();
        $id = Db::name('link')->insertGetId($params);
        $h5Host = config('app.env') == 'sandbox' ? config('h5.base_url.sandbox') : config('h5.base_url.prod');

        if (!empty($params['is_capitalization'])) {
            if ($params['media_id'] == 5 || $params['media_id'] == 6) {
                // h5
                $externalLink = 'https://' . $h5Host . '/components/yjy-video-slide/yjy-video-slide?video_id=' . $params['video_id'] . '&video_detail_id=' . $params['video_detail_id'] . '&type=' . $params['media_id'] . '&link_id=' . $id . '&source=link';
            } else {
                $externalLink = 'pages/index/index?video_id=' . $params['video_id'] . '&video_detail_id=' . $params['video_detail_id'] . '&type=' . $params['media_id'] . '&link_id=' . $id . '&source=link&is_capitalization=true';
            }
        } else {
            if ($params['media_id'] == 5 || $params['media_id'] == 6) {
                // h5
                $externalLink = 'https://' . $h5Host . '/components/yjy-video-slide/yjy-video-slide?video_id=' . $params['video_id'] . '&video_detail_id=' . $params['video_detail_id'] . '&type=' . $params['media_id'] . '&link_id=' . $id . '&source=link';
            } else {
                $externalLink = 'https://' . config('app.app_host') . '/jump.php?link_id=' . $id . '&video_id=' . $params['video_id'] . '&video_detail_id=' . $params['video_detail_id'] . '&type=' . $params['media_id'];
            }

        }

        $saveData = [
            'id' => $id,
            'external_link' => $externalLink,
            'updated_at' => time()
        ];

        Db::name('link')->save($saveData);

        return ['external_link' => $externalLink];
    }

    // 获取收藏数据
    public function getCollectionData($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $officialAccountId = $userInfo['cps_used_official_account_id'];


        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $where[] = ['l.responsibility_person_id', 'in', $responsibilityPersonIds];
        } elseif (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id, name');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonName = array_column($responsibilityPersonData, 'name', 'id');
            $where[] = ['l.responsibility_person_id', 'in', $responsibilityPersonIds];
            $where[] = ['l.official_account_id', '=', $officialAccountId];
        } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $where[] = ['l.responsibility_person_id', '=', $responsibilityPersonId];
            $where[] = ['l.official_account_id', '=', $officialAccountId];
        } else {
            $where[] = ['l.official_account_id', '=', $officialAccountId];
        }

        // 投放媒体media_id
        if (!empty($params['media_id'])) {
            $where[] = ['l.media_id', '=', $params['media_id']];
        }
        // 链接id
        if (!empty($params['id'])) {
            $where[] = ['l.id', '=', $params['id']];
        }
        // 短剧id
        if (!empty($params['video_id'])) {
            $where[] = ['l.video_id', '=', $params['video_id']];
        }

        // 备注搜索
        if (!empty($params['remark'])) {
            $where[] = ['l.remark', 'like', '%' . $params['remark'] . '%'];
        }

        // 添加时间搜索
        if (!empty($params['created_at'])) {
            $startTime = strtotime($params['created_at']);
            $where[] = ['l.created_at', '>=', $startTime];

            $endTime = strtotime($params['created_at'] . ' 23:59:59');
            $where[] = ['l.created_at', '<=', $endTime];
        }

        $model = Db::name('collection_link')->alias('c')->join('link l', 'l.id = c.link_id')->where($where);
        $total = $model->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $fields = 'l.id, l.url, l.media_id, l.video_id, l.video_detail_id, l.is_open, l.echo_rule_config_id, l.recharge_template_id, l.external_link, l.created_at, l.echo_rate, l.recharge_price, l.remark, l.advertiser_id, l.link_switch, l.rebate, l.responsibility_person_id, l.video_pay_setting_id, l.designated_amount_echo, l.design_switch, l.link_type, l.is_new_recharge_setting, l.is_new_back_setting';
        $totalPage = ceil($total / $limit);

        $offset = ($page - 1) * $limit;
        $data = $model->field($fields)->order('c.id desc')->limit($offset, $limit)->select()->toArray();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 获取推广链接列表
    public function getLinkList($params, $userInfo)
    {
        $officialAccountId = $userInfo['cps_used_official_account_id'];
        if (!empty($params['is_collection'])) {
            // 获取收藏的链接列表
            $data = $this->getCollectionData($params, $userInfo);
        } else {
            //
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 10;
            $where = [];

            $responsibilityPersonId = $userInfo['cps_user_id'];
            $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

            if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
                // 分公司
                $cpsUserId = $userInfo['cps_user_id'];
                $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
                $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
                $responsibilityPersonIds[] = $cpsUserId;
                $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
            } elseif (!empty($distributorInfo['is_distributor'])) {
                // 分销商能查看他下面的投手的数据
                $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id, name');
                $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
                $responsibilityPersonName = array_column($responsibilityPersonData, 'name', 'id');
                $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIds];
                $where[] = ['official_account_id', '=', $officialAccountId];
            } elseif ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
                $where[] = ['responsibility_person_id', '=', $userInfo['cps_user_id']];
                $where[] = ['official_account_id', '=', $officialAccountId];
            } else {
                $where[] = ['official_account_id', '=', $officialAccountId];
            }

            // 投放媒体media_id
            if (!empty($params['media_id'])) {
                $where[] = ['media_id', '=', $params['media_id']];
            }
            // 投放广告账号ID
            if (!empty($params['advertiser_id'])) {
                $where[] = ['advertiser_id', '=', $params['advertiser_id']];
            }
            // 链接id
            if (!empty($params['id'])) {
                $where[] = ['id', '=', $params['id']];
            }
            // 短剧id
            if (!empty($params['video_id'])) {
                $where[] = ['video_id', '=', $params['video_id']];
            }

            // 备注搜索
            if (!empty($params['remark'])) {
                $where[] = ['remark', 'like', '%' . $params['remark'] . '%'];
            }

            // 投手搜索
            if (!empty($params['responsibility_person_id'])) {
                $where[] = ['responsibility_person_id', '=', $params['responsibility_person_id']];
            }

            // 添加时间搜索
            if (!empty($params['created_at'])) {
                $startTime = strtotime($params['created_at']);
                $where[] = ['created_at', '>=', $startTime];

                $endTime = strtotime($params['created_at'] . ' 23:59:59');
                $where[] = ['created_at', '<=', $endTime];
            }

            $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, url, media_id, video_id, video_detail_id, is_open, echo_rule_config_id, recharge_template_id, external_link, created_at, echo_rate, recharge_price, remark, advertiser_id, link_switch, rebate, responsibility_person_id, video_pay_setting_id, designated_amount_echo, design_switch, link_type, is_new_recharge_setting, is_new_back_setting');
        }

        if (!empty($data['data'])) {
            // 当前公众号信息
            $isH5Official = false;
            $currentOfficial = $userInfo['cps_official_accounts_data'];
            foreach ($currentOfficial as $official) {
                if ($official['id'] == $officialAccountId && in_array($official['app_id'], config('h5.officials'))) {
                    $isH5Official = true;
                    break;
                }
            }
            // 投放媒体数据
            $mediaData = array_column(config('enum.launch_media'), 'name', 'id');

            $linkIds = $videoIds = $videoDetailIds = $echoRuleConfigIds = $rechargeTemplateIds = $videoPaySettingIds = $customRechargeTemplateIds = [];
            foreach ($data['data'] as $key => $item) {

                $linkIds[] = $item['id'];
                $videoIds[] = $item['video_id'];
                $videoDetailIds[] = $item['video_detail_id'];

                if ($item['is_new_back_setting'] == 2) {
                    $echoRuleConfigIds[] = $item['echo_rule_config_id'];
                }

                if ($item['is_new_recharge_setting'] == 1) {
                    if ($item['video_pay_setting_id'] != 0) {
                        $videoPaySettingIds[] = $item['video_pay_setting_id'];
                    }

                    if ($item['recharge_template_id'] != 0) {
                        $rechargeTemplateIds[] = $item['recharge_template_id'];
                    }
                } else {
                    $customRechargeTemplateIds[] = $item['recharge_template_id'];
                }
                
                // if ($isH5Official) {
                //     $externalLink = explode('?', $item['external_link']);
                //     $data['data'][$key]['external_link'] = config('h5.external_link') . '?' . $externalLink[1];
                // }

            }

            // 收藏数据
            $collectionData = $this->collectionLinkModel->getDataByWhere(['link_id' => $linkIds, 'official_account_id' => $userInfo['cps_used_official_account_id']], 'id, link_id');
            $collection = array_column($collectionData, 'id', 'link_id');

            // 短剧数据
            $videos = $this->videosModel->getDataByWhere(['id' => $videoIds], 'id, name');
            $videoData = array_column($videos, 'name', 'id');

            // 短剧剧集数据
            $videoDetails = $this->detailModel->getInfoByIds($videoDetailIds, 'id, sort');
            $videoDetailData = array_column($videoDetails, 'sort', 'id');

            // 自定义回传设置
            if ($echoRuleConfigIds) {
                $echoRuleConfigs = $this->echoRuleConfigModel->getDataByWhere(['id' => $echoRuleConfigIds], 'id, name, back_rate_type, echo_rate, pass, leak');
                $echoRuleConfigData = array_column($echoRuleConfigs, NULL, 'id');
            }

            // 自定义充值设置
            if ($rechargeTemplateIds) {
                $rechargeTemplates = $this->rechargeTemplateModel->getDataByWhere(['id' => $rechargeTemplateIds], 'id, name');
                $rechargeTemplateData = array_column($rechargeTemplates, 'name', 'id');
            }

            // 自定义短剧收费设置
            if ($videoPaySettingIds) {
                $videoPayConfig = $this->videoPayConfigModel->getDataByWhere(['id' => $videoPaySettingIds], 'id, name');
                $videoPayConfigData = array_column($videoPayConfig, 'name', 'id');
            }

            // 新版自定义收费设置
            if ($customRechargeTemplateIds) {
                $customRechargeTemplate = $this->customRechargeTemplateModel->getDataByWhere(['id' => $customRechargeTemplateIds], 'id, name');
                $customRechargeTemplateData = array_column($customRechargeTemplate, 'name', 'id');
            }

            $toDay = date('Ymd');
            // 今日激活用户数据
            $registerUsers = $this->userModel->getBatchDataByWhere([['link_id', 'in', $linkIds], ['activation_time', '>=', date('Y-m-d') . ' 00:00:00']], 'link_id, id');
            $registerUserData = $toDayUserIds = [];
            foreach ($registerUsers as $item) {
                $registerUserData[$item['link_id']][] = $item['id'];
                $toDayUserIds[] = $item['id'];
            }

            // 今日充值数据
            $rechargeData = $userData = $userRechargeData = [];
            $payRecordData = $this->payRecordModel->getInfo(['consume_date' => $toDay, 'link_id' => $linkIds, 'status' => 1], 'link_id, uid, total_fee, activation_date');

            if ($payRecordData) {
                foreach ($payRecordData as $key => $value) {

                    $rechargeData[$value['link_id']][] = $value['total_fee'];
                    $userData[$value['link_id']][] = $value['uid'];

                    $userRechargeData[$value['link_id']][] = ['uid' => $value['uid'], 'total_fee' => $value['total_fee'], 'activation_date' => $value['activation_date']];
                }
            }

            // 获取统计的投放链接数据
            $dailyDeliveryData = $this->dailyDeliveryDataModel->getDataByWhere(['link_id' => $linkIds], 'link_id, actual_cost, date, conversion_number, total_recharge');
            $dailyDeliveryCost = $conversionNumber = $linkTotalRecharge = [];
            $within5DaysDate = date('Ymd', time() - 86400 * 4); // 3日内

            $within5DaysRecharge = $within5DaysRechargeUserNum = [];
            foreach ($dailyDeliveryData as $item) {

                if (empty($dailyDeliveryCost[$item['link_id']])) {
                    $dailyDeliveryCost[$item['link_id']] = 0;
                }
                $dailyDeliveryCost[$item['link_id']] += $item['actual_cost']; // 累计花费

                if (empty($conversionNumber[$item['link_id']])) {
                    $conversionNumber[$item['link_id']] = 0;
                }
                $conversionNumber[$item['link_id']] += $item['conversion_number']; // 累计充值人数

                if (empty($linkTotalRecharge[$item['link_id']])) {
                    $linkTotalRecharge[$item['link_id']] = 0;
                }
                $linkTotalRecharge[$item['link_id']] += $item['total_recharge']; // 累计充值金额

                if ($item['date'] > $within5DaysDate && $item['date'] < date('Ymd')) {
                    if (empty($within5DaysRecharge[$item['link_id']])) {
                        $within5DaysRecharge[$item['link_id']] = 0;
                    }
                    $within5DaysRecharge[$item['link_id']] += $item['total_recharge']; // 3日内累计充值金额

                    if (empty($within5DaysRechargeUserNum[$item['link_id']])) {
                        $within5DaysRechargeUserNum[$item['link_id']] = 0;
                    }
                    $within5DaysRechargeUserNum[$item['link_id']] += $item['conversion_number']; // 3日内累计充值人数
                }
            }

            //抖音媒资参数获取
            list($dy_videos, $dy_details) = ThirdVideos::getDyMediaParam($videoIds, $videoDetailIds);
            foreach ($data['data'] as $key => $item) {
                // 是否收藏
                $data['data'][$key]['is_collection'] = empty($collection[$item['id']]) ? 0 : 1;

                $data['data'][$key]['media_name'] = empty($mediaData[$item['media_id']]) ? '' : $mediaData[$item['media_id']];

                $data['data'][$key]['video_name'] = empty($videoData[$item['video_id']]) ? '' : $videoData[$item['video_id']];

                $data['data'][$key]['sort'] = empty($videoDetailData[$item['video_detail_id']]) ? '' : $videoDetailData[$item['video_detail_id']];

                if ($item['is_new_back_setting'] == 1) {
                    if ($item['echo_rule_config_id'] == 0) {
                        $data['data'][$key]['echo_rule_config_name'] = '按公共配置';
                    } else if ($item['echo_rule_config_id'] == 1) {
                        $data['data'][$key]['echo_rule_config_name'] = '按自然日';
                    } else if ($item['echo_rule_config_id'] == 2) {
                        $data['data'][$key]['echo_rule_config_name'] = '仅回传首单';
                    }
                } else {
                    $data['data'][$key]['echo_rule_config_name'] = empty($echoRuleConfigData[$item['echo_rule_config_id']]) ? '' : $echoRuleConfigData[$item['echo_rule_config_id']]['name'];

                    if (!empty($echoRuleConfigData[$item['echo_rule_config_id']]) && $echoRuleConfigData[$item['echo_rule_config_id']]['back_rate_type'] == 0) {
                        $data['data'][$key]['echo_rate'] = $echoRuleConfigData[$item['echo_rule_config_id']]['echo_rate'];
                    } else if (!empty($echoRuleConfigData[$item['echo_rule_config_id']]) && $echoRuleConfigData[$item['echo_rule_config_id']]['back_rate_type'] == 1) {
                        $data['data'][$key]['echo_rate'] = $echoRuleConfigData[$item['echo_rule_config_id']]['pass'] .':'. $echoRuleConfigData[$item['echo_rule_config_id']]['leak'];
                    }
                }

                if ($item['is_new_recharge_setting'] == 1) {
                    if ($item['recharge_template_id'] != 0) {
                        $data['data'][$key]['recharge_template_name'] = empty($rechargeTemplateData[$item['recharge_template_id']]) ? '' : $rechargeTemplateData[$item['recharge_template_id']];
                    } else {
                        $data['data'][$key]['recharge_template_name'] = '按公共配置';
                    }

                    $data['data'][$key]['video_pay_setting_name'] = empty($videoPayConfigData[$item['video_pay_setting_id']]) ? '' : $videoPayConfigData[$item['video_pay_setting_id']];
                } else {
                    $data['data'][$key]['recharge_template_name'] = empty($customRechargeTemplateData[$item['recharge_template_id']]) ? '' : $customRechargeTemplateData[$item['recharge_template_id']];
                    $data['data'][$key]['video_pay_setting_name'] = '';
                }

                // 今日注册用户数
                $data['data'][$key]['register_user_num'] = empty($registerUserData[$item['id']]) ? 0 : count($registerUserData[$item['id']]);

                if (empty($userData[$item['id']])) {

                    // 今日充值人数
                    $data['data'][$key]['recharge_user_num'] = 0;
                    // 今日新用户充值人数
                    $data['data'][$key]['new_user_recharge_num'] = 0;
                    // 今日新用户充值金额
                    $data['data'][$key]['new_user_recharge_price'] = 0;
                    // 今日新用户充值笔数
                    $data['data'][$key]['new_user_recharge_number'] = 0;

                } else {

                    $userIds = array_unique($userData[$item['id']]);
                    // 今日充值人数
                    $data['data'][$key]['recharge_user_num'] = count($userIds);

                    // 今日新用户充值人数
                    // $newUserIds = array_intersect($userIds, $toDayUserIds);

                    $data['data'][$key]['new_user_recharge_num'] = 0;
                    $data['data'][$key]['new_user_recharge_number'] = 0;
                    $data['data'][$key]['new_user_recharge_price'] = 0;

                    // 今日新用户充值金额
                    if (!empty($userRechargeData[$item['id']])) {
                        $price = 0;
                        $newUserRechargeNumber = 0;
                        $newUserRechargeNum = [];
                        foreach ($userRechargeData[$item['id']] as $value) {
                            if ($value['activation_date'] == $toDay) {
                                $price += $value['total_fee'];
                                // 今日新用户充值笔数
                                $newUserRechargeNumber += 1;
                                $newUserRechargeNum[] = $value['uid'];
                            }
                        }
                        $data['data'][$key]['new_user_recharge_number'] = $newUserRechargeNumber;
                        $data['data'][$key]['new_user_recharge_price'] = round($price, 2);
                        $data['data'][$key]['new_user_recharge_num'] = count(array_unique($newUserRechargeNum));
                    }
                }

                if (empty($item['recharge_price'])) {
                    $data['data'][$key]['recharge_price'] = 0;
                }

                // 今日总充值金额
                $data['data'][$key]['today_recharge_price'] = empty($rechargeData[$item['id']]) ? 0 : number_format(array_sum($rechargeData[$item['id']]), 2);

                // 今日充值笔数
                $data['data'][$key]['today_recharge_num'] = empty($rechargeData[$item['id']]) ? 0 : count($rechargeData[$item['id']]);

                // 累计花费
                $data['data'][$key]['total_cost'] = empty($dailyDeliveryCost[$item['id']]) ? 0 : round($dailyDeliveryCost[$item['id']], 2);

                // 历史人均贡献
                $data['data'][$key]['history_per_capita_contribution'] = empty($conversionNumber[$item['id']]) ? 0 : round($linkTotalRecharge[$item['id']] / $conversionNumber[$item['id']], 2);

                // 3日内人均贡献
                $data['data'][$key]['per_capita_contribution_within_5_days'] = empty($within5DaysRechargeUserNum[$item['id']]) ? 0 : round($within5DaysRecharge[$item['id']] / $within5DaysRechargeUserNum[$item['id']], 2);
                // 负责人
                if (!empty($distributorInfo['is_distributor'])) {
                    $data['data'][$key]['responsibility_person_name'] = empty($responsibilityPersonName[$item['responsibility_person_id']]) ? '' : $responsibilityPersonName[$item['responsibility_person_id']];
                    $data['data'][$key]['is_distributor'] = 1; // 是否是分销商或者是分销商下面的投手 用于LTV统计请求不同的接口
                } else {
                    $responsibilityPersonData = $this->responsibilityPersonModel->getInfoById($item['responsibility_person_id'], 'pid, is_distributor');
                    $data['data'][$key]['responsibility_person_name'] = '';
                    if (!empty($responsibilityPersonData['pid']) || !empty($responsibilityPersonData['is_distributor'])) {
                        $data['data'][$key]['is_distributor'] = 1; // 是否是分销商或者是分销商下面的投手 用于LTV统计请求不同的接口
                    } else {
                        $data['data'][$key]['is_distributor'] = 0; // 是否是分销商或者是分销商下面的投手 用于LTV统计请求不同的接口
                    }
                }

                // 指定金额回传
                if (!empty($item['designated_amount_echo'])) {
                    $data['data'][$key]['designated_amount_echo'] = json_encode($item['designated_amount_echo'], true);
                }

                // start by add huangxiaoshan 20230720
                $data['data'][$key]['douyin_link'] = '';
                if ($item['link_type'] == 2) { // 抖音推广
                    $params = 'link_id=' . $item['id'] . '&video_id=' . $item['video_id'] . '&video_detail_id=' . $item['video_detail_id'] . '&type=1&source=link';
                    $album_id = $dy_videos[$item['video_id']] ?? '';
                    $episode_id = $dy_details[$item['video_detail_id']] ?? '';
                    if ($album_id && $episode_id) {
                        $as_param = '&tt_album_id=' . $album_id . '&tt_episode_id=' . $episode_id;
                        $params .= $as_param;
                        $data['data'][$key]['external_link'] = $item['external_link'] . $as_param;
                    }
                    $data['data'][$key]['douyin_link'] = $params;
                }
                $data['data'][$key]['link_type_text'] = ($item['link_type'] == 2 ? '抖音小程序' : ($item['link_type'] == 1 ? '微信小程序' : ''));
                // end
            }
        }

        return $data;
    }

    // 链接收藏/取消收藏
    public function collectionLink($id, $userInfo)
    {
        $where = $saveData = [
            'link_id' => $id,
            'official_account_id' => $userInfo['cps_used_official_account_id']
        ];

        $data = $this->collectionLinkModel->getInfoByWhere($where);
        if ($data) {
            $bool = $this->collectionLinkModel->destroy($data['id']);
        } else {
            $saveData['created_at'] = time();
            $saveData['responsibility_person_id'] = $userInfo['cps_user_id'];
            $bool = $this->collectionLinkModel->edit($saveData);
        }

        return $bool ? true : false;
    }

    // 推广链接详情
    public function getLinkDetail($id)
    {
        $data = $this->model->getInfoByWhere(['id' => $id], 'id, url, media_id, video_id, video_detail_id, is_open, echo_rate, echo_rule_config_id, recharge_template_id, is_open_low_recharge_not_echo, not_echo_recharge_price, remark, advertiser_id, link_switch, version, project_id, token, rebate, is_capitalization, subject_id, video_pay_setting_id, designated_amount_echo, design_switch, link_type');

        return $data;
    }

    // 存储快手磁力监测链接拿到的数据到redis
    public function saveKwaiMonitoringLinkData($params)
    {
        file_put_contents('./kwai_monitoring_link.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($params) . ';' . PHP_EOL, FILE_APPEND);

        if ($params['os'] == 0) {
            // 安卓
            $regx = '/Build(.*?) /is';
            preg_match($regx, $params['ua'], $match);

            if (empty($match[1])) {
                return;
            }
            $userAgent = $match[1];
        } else {
            // iOS
            $regx = '/\((.*?)\)/';
            preg_match($regx, $params['ua'], $match);
            $userAgent = $match[1];

        }

        $userAgent = strtoupper(str_replace(' ', '', $userAgent));

        $redis = Cache::store('redis')->handler();
        $ip = $params['ip'];
        $linkId = !empty($params['link_id']) ? $params['link_id'] : '';
        $clickid = $params['callback'];

        $redis->select(6);
        $data = [
            'advertiser_id' => $params['aid'],
            'clickid' => $clickid,
            'ip' => $ip,
            'ua' => $userAgent,
            'link_id' => $linkId
        ];

        $redis->set(md5($ip . $userAgent . $linkId), json_encode($data), 7200);
        if (!empty($params['is_capitalization'])) {
            $redis->set(md5($clickid), json_encode($data), 7200);
        }
    }

    // 存储抖音1.0巨量监测链接拿到的数据到redis
    public function saveMonitoringLinkData($params)
    {
        if ($params['mobile_system'] == 0) {
            // 安卓
            $regx = '/Build(.*?) /is';
            preg_match($regx, $params['ua'], $match);

            if (empty($match[1])) {
                return;
            }
            $userAgent = $match[1];
        } else {
            // iOS
            $regx = '/\((.*?)\)/';
            preg_match($regx, $params['ua'], $match);
            $userAgent = $match[1];

        }

        $userAgent = strtoupper(str_replace(' ', '', $userAgent));

        $ip = $params['ip'];
        $linkId = $params['link_id'];

        file_put_contents('./monitoring_link.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($params) . ';' . PHP_EOL, FILE_APPEND | LOCK_EX);

        $clickid = $params['callback_param'];

        $redis = Cache::store('redis')->handler();
        $redis->select(6);

        $data = [
            'advertiser_id' => $params['adgroup_id'],
            'clickid' => $clickid,
            'ip' => $ip,
            'ua' => $userAgent,
            'link_id' => $linkId
        ];

        $redis->set(md5($ip . $userAgent . $linkId), json_encode($data), 7200);
    }

    // 存储抖音2.0巨量监测链接拿到的数据到redis
    public function saveTiktokMonitoringLinkData($params)
    {
        file_put_contents('./tiktok_monitoring_link.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($params) . ';' . PHP_EOL, FILE_APPEND | LOCK_EX);
        try {
            if ($params['os'] == 0) {
                // 安卓
                $regx = '/Build(.*?) /is';
                preg_match($regx, $params['ua'], $match);

                if (empty($match[1])) {
                    return;
                }
                $userAgent = $match[1];
            } else {
                // iOS
                $regx = '/\((.*?)\)/';
                preg_match($regx, $params['ua'], $match);
                $userAgent = $match[1];

            }

            $userAgent = strtoupper(str_replace(' ', '', $userAgent));
            $ip = $params['ip'];
            $linkId = $params['link_id'];

            $clickid = $params['callback_param'];

            $redis = Cache::store('redis')->handler();
            $redis->select(6);

            $data = [
                'advertiser_id' => $params['promotion_id'],
                'clickid' => $clickid,
                'ip' => $ip,
                'ua' => $userAgent,
                'link_id' => $linkId
            ];

            $redis->set(md5($ip . $userAgent . $linkId), json_encode($data), 7200);
            $redis->set(md5($userAgent . $linkId), json_encode($data), 7200);
        } catch (\Exception $e) {
            Log::error('****** ' . json_encode($params) . ' --//-- ' . '第 ' . $e->getLine() . ' 行' . '：' . $e->getMessage());
        }
    }

    /**
     * 获取巨量accessToken
     *
     * @dateTime 2022/12/07
     * @param string authCode
     * @author laoliu
     */
    public function getHugeAmountAccessToken($authCode)
    {
        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $url = 'https://ad.oceanengine.com/open_api/oauth2/access_token/';

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'grant_type' => 'auth_code',
            'auth_code' => $authCode
        ];
        $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

        $result = json_decode($result, true);

        if ($result['code']) {
            return;
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('redis_key.huge_amount_access_token'), $result['data']['access_token'], $result['data']['expires_in']);
        $redis->set(config('redis_key.huge_amount_refresh_token'), $result['data']['refresh_token'], $result['data']['refresh_token_expires_in']);
    }

    /**
     * 获取快手磁力智投accessToken
     *
     * @dateTime 2022/12/07
     * @param string authCode
     * @author laoliu
     */
    public function getKwaiAccessToken($authCode)
    {
        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $url = 'https://ad.e.kuaishou.com/rest/openapi/oauth2/authorize/access_token';

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'auth_code' => $authCode
        ];

        $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

        $result = json_decode($result, true);

        if ($result['code']) {
            return;
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('kwai.magnetic_force_access_token'), $result['data']['access_token'], $result['data']['access_token_expires_in']);
        $redis->set(config('kwai.magnetic_force_refresh_token'), $result['data']['refresh_token'], $result['data']['refresh_token_expires_in']);
        // $redis->set(config('kwai.magnetic_force_advertiser_ids'), json_encode($result['data']['advertiser_ids']), $result['data']['access_token_expires_in']);
        $this->kwaiAccountManager($result['data']['advertiser_ids']);
    }

    // 快手账户管理
    public function kwaiAccountManager($advertiserIds)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $advertiserData = $redis->get(config('kwai.magnetic_force_advertiser_ids'));
        $advertiserData = json_decode($advertiserData, true);

        if (!empty($advertiserData)) {

            $newAdvertiserIds = [];
            foreach ($advertiserIds as $value) {
                if (!in_array($value, $advertiserData)) {
                    $newAdvertiserIds[] = $value;
                }
            }

            $advertiserData = array_merge($advertiserData, $newAdvertiserIds);
            $redis->set(config('kwai.magnetic_force_advertiser_ids'), json_encode($advertiserData));
        } else {
            $redis->set(config('kwai.magnetic_force_advertiser_ids'), json_encode($advertiserIds));
        }
    }

    // 获取百度营销token
    public function getBaiduMarketingToken($params)
    {
        $secret = config('baidu.secret_key');
        $url = 'https://u.baidu.com/oauth/accessToken';

        $requestData = [
            'appId' => $params['appId'],
            'secretKey' => $secret,
            'authCode' => $params['authCode'],
            'grantType' => 'auth_code',
            'userId' => $params['userId']
        ];

        $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type:application/json;charset:utf-8;']);

        $result = json_decode($result, true);

        if ($result['code'] != 0) {
            return;
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('baidu.access_token'), $result['data']['accessToken'], $result['data']['expiresIn']);
        $redis->set(config('baidu.refresh_token'), $result['data']['refreshToken'], $result['data']['refreshExpiresIn']);
        $redis->set(config('baidu.open_id'), $result['data']['openId'], $result['data']['refreshExpiresIn']);
        $redis->set(config('baidu.baidu_user_id'), $params['userId'], $result['data']['refreshExpiresIn']);
        $this->getBaiduUserInfo();
    }

    // 获取百度信息、子账号
    public function getBaiduUserInfo()
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $token = Common::getBaiduAccessToken();

        $requestData = [
            'openId' => $redis->get(config('baidu.open_id')),
            'accessToken' => $token,
            'userId' => $redis->get(config('baidu.baidu_user_id')),
            'needSubList' => true,
            'lastPageMaxUcId' => 1
        ];

        $result = Common::curlRequest('https://u.baidu.com/oauth/getUserInfo', 'POST', json_encode($requestData), ['Content-Type:application/json;charset:utf-8;']);

        $result = json_decode($result, true);

        if ($result['code'] == 0 && !empty($result['data']['subUserList'])) {
            $subUserList = $result['data']['subUserList'];
            $key = config('baidu.baidu_sub_user_list');
            $data = $redis->hGetAll($key);
            // dump($data);die;

            foreach ($subUserList as $value) {
                if (!$redis->hExists($key, $value['ucId'])) {
                    $redis->hSet($key, $value['ucId'], $value['ucName']);
                }
            }

            return $data;
        }
    }

    // 刷新巨量开发者平台accessToken
    public function refreshAccessToken()
    {
        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $url = 'https://ad.oceanengine.com/open_api/oauth2/refresh_token/';
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $refreshToken = $redis->get(config('redis_key.huge_amount_refresh_token'));

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'grant_type' => 'refresh_token',
            'refresh_token' => $refreshToken
        ];
        $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

        $result = json_decode($result, true);

        if ($result['code']) {
            return;
        }

        $redis->set(config('redis_key.huge_amount_access_token'), $result['data']['access_token'], $result['data']['expires_in']);
        $redis->set(config('redis_key.huge_amount_refresh_token'), $result['data']['refresh_token'], $result['data']['refresh_token_expires_in']);
    }

    // 获取巨量纵横组织账户下的所有广告账户信息
    public function getAccountSelectList($params)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        if (!empty($params['subject_id']) && $params['subject_id'] == 8) {
            $redisKey = config('redis_key.huge_amount_yishu_advertising_account_info');
        } elseif (!empty($params['subject_id']) && $params['subject_id'] == 24) {
            $redisKey = config('redis_key.huge_amount_xingcan_advertising_account_info');
        } else {
            $redisKey = config('redis_key.huge_amount_advertising_account_info');
        }

        $length = $redis->scard($redisKey);
        $data = [];

        if ($length && empty($params['is_refresh'])) {
            $result = $redis->smembers($redisKey);

            foreach ($result as $item) {
                $data[] = json_decode($item, true);
            }

            // 光标事件搜索
            if (!empty($params['advertiser_name'])) {
                $searchData = [];
                foreach ($data as $key => $value) {
                    if (strstr($value['advertiser_name'], $params['advertiser_name'])) {
                        $searchData[] = $value;
                    }
                }
                return $searchData;
            }
            return $data;
        }

        if (!empty($params['subject_id']) && $params['subject_id'] == 8) {
            $appId = config('tiktok.huge_amount_yaodao.app_id');
            $secret = config('tiktok.huge_amount_yaodao.secret');
        } elseif (!empty($params['subject_id']) && $params['subject_id'] == 24) {
            $appId = config('tiktok.huge_amount_xingcan.app_id');
            $secret = config('tiktok.huge_amount_xingcan.secret');
        } else {
            $appId = config('tiktok.huge_amount.app_id');
            $secret = config('tiktok.huge_amount.secret');
        }

        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);
        $url = 'https://ad.oceanengine.com/open_api/oauth2/advertiser/get/';

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'access_token' => $accessToken
        ];

        $result = Common::_curl($url, $requestData, 'GET', ['json' => 1]);

        $result = json_decode($result, true);

        if ($result['code']) {
            return ['message' => $result['message']];
        }
        $redis->del($redisKey);

        $url = 'https://ad.oceanengine.com/open_api/2/majordomo/advertiser/select/';
        $hearder['headers'] = ['Access-Token:' . $accessToken];

        foreach ($result['data']['list'] as $key => $value) {

            if (empty($value['advertiser_id'])) {
                continue;
            }
            $advertiserId = $value['advertiser_id'];
            $requestData = ['advertiser_id' => $advertiserId];

            $result = Common::_curl($url, $requestData, 'GET', $hearder);
            $result = json_decode($result, true);
            if (!$result['code']) {
                foreach ($result['data']['list'] as $key => $value) {
                    $data[] = $value;
                    $redis->sadd($redisKey, json_encode($value));
                }
            }
        }

        $redis->expire($redisKey, 86400);

        return $data;
    }

    /**
     * 快手账户下拉列表
     *
     * @dateTime 2022/12/08
     * @return string|array
     * @author zhixiang0215@126.com
     */
    public function getKwaiAccountSelectList($params)
    {
        $kwaiId = config('kwai.kwai_id');

        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $redisKey = config('kwai.magnetic_force_advertising_account_info');
        $length = $redis->scard($redisKey);
        $data = [];

        if ($length && empty($params['is_refresh'])) {
            $result = $redis->smembers($redisKey);

            foreach ($result as $item) {
                $data[] = json_decode($item, true);
            }

            // 光标事件搜索
            if (!empty($params['advertiser_name'])) {
                $searchData = [];
                foreach ($data as $key => $value) {
                    if (strstr($value['advertiser_name'], $params['advertiser_name'])) {
                        $searchData[] = $value;
                    }
                }
                return $searchData;
            }
            return $data;
        }

        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $accessToken = Common::getKwaiAccessToken($appId, $secret);

        $url = 'https://ad.e.kuaishou.com/rest/openapi/gw/uc/v1/advertisers';

        $header['headers'] = ['Access-Token:' . $accessToken, 'Content-Type: application/json'];
        $header['json'] = 1;
        $requestData = ['advertiser_id' => $kwaiId];
        $result = Common::_curl($url, $requestData, 'POST', $header);

        $result = json_decode($result, true);

        if ($result['code']) {
            return ['message' => $result['message']];
        }
        $redis->del($redisKey);

        foreach ($result['data']['details'] as $key => $value) {
            if (empty($value['advertiser_id'])) {
                continue;
            }
            if (!empty($value['corporation_name'])) {
                unset($value['corporation_name']);
            }
            $data[] = $value;
            $redis->sadd($redisKey, json_encode($value));
        }

        $redis->expire($redisKey, 43200);

        return $data;
    }

    // 存储百度监测链接数据
    public function saveBaiduMonitoringLinkData($params)
    {
        file_put_contents('./baidu_monitoring_link.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($params) . ';' . PHP_EOL, FILE_APPEND);

        if ($params['os'] == 0) {
            // 安卓
            $regx = '/Build(.*?)\) /is';
            preg_match($regx, $params['ua'], $match);

            if (empty($match[1])) {
                return;
            }
            $userAgent = $match[1];
        } else {
            // iOS
            $regx = '/\((.*?)\)/';
            preg_match($regx, $params['ua'], $match);
            $userAgent = $match[1];

        }

        $userAgent = strtoupper(str_replace(' ', '', $userAgent));

        $redis = Cache::store('redis')->handler();
        $ip = $params['ip'];
        $clickid = $params['bd_vid'];

        $redis->select(6);
        $data = [
            'advertiser_id' => $params['uid'],
            'clickid' => $clickid,
            'ip' => $ip,
            'ua' => $userAgent,
        ];

        $redis->set(md5($ip . $userAgent . $params['link_id']), json_encode($data), 7200);
        $redis->set(md5($clickid . $params['link_id']), json_encode($data), 7200);
    }

    // 微博回调存储code值
    public function saveWeiboCode($params)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('weibo.callback_code'), $params['code']);
    }

    // 存储微博监测数据
    public function saveWeiboMonitoringLinkData($params)
    {
        file_put_contents('./weibo_monitoring_link.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($params) . ';' . PHP_EOL, FILE_APPEND);
    }

    // 存储腾讯监测链接数据
    public function saveTencentMonitoringLinkData($params)
    {
        file_put_contents('./tencent_monitoring_link.txt', date('Y-m-d H:i:s') . ' ：' . json_encode($params) . ';' . PHP_EOL, FILE_APPEND);

        $redis = Cache::store('redis')->handler();
        $redis->select(6);

        $data = [
            'callback' => $params['callback'],
            'click_id' => $params['click_id'],
            'advertiser_id' => $params['adgroup_id'],
        ];

        $redis->set(md5($params['wechat_openid']), json_encode($data), 14400);
    }

    // 获取跳转微信小程序地址
    public function getWechatUrlScheme($params)
    {
        // file_put_contents('./baidu_monitoring_link.txt', date('Y-m-d H:i:s').' ：'.json_encode($params).';'.PHP_EOL, FILE_APPEND);die;
        // 记录日志
        $log = fopen('./baidu_monitoring_link_test.txt', 'a+');
        fwrite($log, date('Y-m-d H:i:s') . '：' . json_encode($params) . PHP_EOL);
        fclose($log);
        $appletData = $this->appletModel->getInfoByWhere(['origin_id' => $params['originId']], 'id, app_id, app_secret');

        $token = Common::getWechatAppletAccessToken($appletData['app_id'], $appletData['app_secret'], $appletData['id']);

        $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $token;
        $path = empty($params['path']) ? config('enum.applet_home_jump_url') : $params['path'];
        $requestData = [
            'jump_wxa' => [
                'path' => $path
            ],
            'is_expire' => true,
            'expire_time' => time() + 30 * 86400
        ];

        $result = Common::curlRequest($url, 'POST', json_encode($requestData));
        $result = json_decode($result, true);
        return [
            'code' => 0,
            'msg' => 'success',
            'result' => [
                'scheme' => $result['openlink']
            ]
        ];
    }

    /**
     * 获取巨量accessToken
     *
     * @dateTime 2022/12/07
     * @param string authCode
     * @author laoliu
     */
    public function getHugeAmountAccessToken1($authCode)
    {

        $url = 'https://ad.oceanengine.com/open_api/oauth2/access_token/';

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'grant_type' => 'auth_code',
            'auth_code' => $authCode
        ];
        $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

        $result = json_decode($result, true);

        if ($result['code']) {
            return;
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('redis_key.huge_amount_access_token') . '-' . $appId, $result['data']['access_token'], $result['data']['expires_in']);
        $redis->set(config('redis_key.huge_amount_refresh_token') . '-' . $appId, $result['data']['refresh_token'], $result['data']['refresh_token_expires_in']);
    }

    /**
     * 获取巨量accessToken
     *
     * @dateTime 2022/12/07
     * @param string authCode
     * @author laoliu
     */
    public function getTiktokSubjectAuthAccessToken($authCode, $objectId)
    {
        if ($objectId == 8) {
            $appId = config('tiktok.huge_amount_yaodao.app_id');
            $secret = config('tiktok.huge_amount_yaodao.secret');
        } elseif ($objectId == 24) {
            $appId = config('tiktok.huge_amount_xingcan.app_id');
            $secret = config('tiktok.huge_amount_xingcan.secret');
        } elseif ($objectId == 5) {
            $appId = config('tiktok.huge_amount_sixseals_erfen.app_id');
            $secret = config('tiktok.huge_amount_sixseals_erfen.secret');
        }

        $url = 'https://ad.oceanengine.com/open_api/oauth2/access_token/';

        $requestData = [
            'app_id' => $appId,
            'secret' => $secret,
            'grant_type' => 'auth_code',
            'auth_code' => $authCode
        ];
        $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

        $result = json_decode($result, true);

        if ($result['code']) {
            return $result['message'];
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $redis->set(config('redis_key.huge_amount_access_token') . '-' . $appId, $result['data']['access_token'], $result['data']['expires_in']);
        $redis->set(config('redis_key.huge_amount_refresh_token') . '-' . $appId, $result['data']['refresh_token'], $result['data']['refresh_token_expires_in']);
    }

    // 创建链接选择主体
    public function createLinkSelectObject($mediaId, $userInfo)
    {
        // $data = empty(config('launch')[$mediaId]) ? [] : config('launch')[$mediaId];
        $cpsUserId = $userInfo['cps_user_id'];
        $companyId = Db::name('responsibility_person')->where(['id' => $cpsUserId])->value('company_id');
        $data = Db::name('subject')->where(['media_id' => $mediaId, 'company_id' => $companyId])->field('id as subject_id, subject, rebate')->select()->toArray();

        return $data;
    }

    // 批量导出
    public function batchExportLink($userInfo, $params = [])
    {
        $link_ids = $params['link_ids'] ?? '';

        if (!$link_ids) {
            return [];
        }

        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();

        $link_ids_array = explode(',', $link_ids);

        // 返回字段
        $field = 'id, url, media_id, video_id, external_link, created_at, echo_rate, is_open, advertiser_id, video_detail_id, link_type, is_new_recharge_setting, is_new_back_setting, echo_rule_config_id, recharge_template_id';

        // 查询条件
        $where = ['id' => $link_ids_array];
        // 获得数据
        $data = $this->model->getDataByWhere($where, $field);

        if ($data) {

            $officialAccountId = $userInfo['cps_used_official_account_id'];

            // 当前公众号信息
            $isH5Official = false;
            $currentOfficial = $userInfo['cps_official_accounts_data'];
            foreach ($currentOfficial ?? [] as $official) {
                if ($official['id'] == $officialAccountId && in_array($official['app_id'], config('h5.officials'))) {
                    $isH5Official = true;
                    break;
                }
            }

            $videoIds = $rechargeTemplateIds = $customRechargeTemplateIds = $echoRuleConfigIds = [];
            // 做点数据处理
            foreach ($data as $key => $val) {
                $videoIds[] = $val['video_id'];
                if ($val['recharge_template_id'] != 0 && $val['is_new_recharge_setting'] == 1) {
                    $rechargeTemplateIds[] = $val['recharge_template_id'];
                }
                if ($val['is_new_recharge_setting'] == 2) {
                    $customRechargeTemplateIds[] = $val['recharge_template_id'];
                }
                if ($val['is_new_back_setting'] == 2) {
                    $echoRuleConfigIds[] = $val['echo_rule_config_id'];
                }
            }

            // 媒体数据
            $mediaData = array_column(config('enum.launch_media'), 'name', 'id');

            // 短剧数据
            $videos = $this->videosModel->getDataByWhere(['id' => $videoIds], 'id, name');
            $videoData = array_column($videos, 'name', 'id');

            // 自定义充值设置
            if ($rechargeTemplateIds) {
                $rechargeTemplates = $this->rechargeTemplateModel->getDataByWhere(['id' => $rechargeTemplateIds], 'id, name');
                $rechargeTemplateData = array_column($rechargeTemplates, 'name', 'id');
            }

            if ($customRechargeTemplateIds) {
                $customRechargeTemplateData = $this->customRechargeTemplateModel->getDataByWhere(['id' => $customRechargeTemplateIds], 'id, name');
                $customRechargeTemplate = array_column($customRechargeTemplateData, 'name', 'id');
            }
            // 自定义回传设置
            if ($echoRuleConfigIds) {
                $echoRuleConfigData = $this->echoRuleConfigModel->getDataByWhere(['id' => $echoRuleConfigIds], 'id, name');
                $echoRuleConfig = array_column($echoRuleConfigData, 'name', 'id');
            }

            // 
            $is_open_array = [1 => '开启', 2 => '关闭'];

            $spreadsheet = new Spreadsheet();

            $worksheet = $spreadsheet->getActiveSheet();

            $worksheet->getDefaultColumnDimension()->setWidth(15);//设置默认列宽
            $worksheet->getColumnDimension('B')->setWidth(100);// 设置列的宽度
            $worksheet->getColumnDimension('C')->setWidth(20);// 设置列的宽度
            $worksheet->getColumnDimension('E')->setWidth(18);// 设置列的宽度
            $worksheet->getColumnDimension('K')->setWidth(18);// 设置列的宽度
            $worksheet->getColumnDimension('L')->setWidth(100);// 设置列的宽度

            $worksheet->setCellValueByColumnAndRow(1, 1, '推广ID');
            $worksheet->setCellValueByColumnAndRow(2, 1, '【微信小程序的】推广链接');

            $worksheet->setCellValueByColumnAndRow(3, 1, '短剧名称');
            $worksheet->setCellValueByColumnAndRow(4, 1, '媒体名称');
            $worksheet->setCellValueByColumnAndRow(5, 1, '创建时间');
            $worksheet->setCellValueByColumnAndRow(6, 1, '充值模板');
            $worksheet->setCellValueByColumnAndRow(7, 1, '回传规则名称');
            $worksheet->setCellValueByColumnAndRow(8, 1, '回传率');
            $worksheet->setCellValueByColumnAndRow(9, 1, '回传开关');
            $worksheet->setCellValueByColumnAndRow(10, 1, '累计充值金额');
            $worksheet->setCellValueByColumnAndRow(11, 1, '广告账号ID');
            $worksheet->setCellValueByColumnAndRow(12, 1, '【抖音小程序的】推广链接');

            // 写入内容
            $line = 0;
            foreach ($data as $key => $val) {
                $line = $key + 2;

                if ($isH5Official) {
                    $externalLink = explode('?', $val['external_link']);
                    $val['external_link'] = config('h5.external_link') . '?' . $externalLink[1];
                }
                // start by add huangxiaoshan 2023-07-20
                $val['douyin_link'] = '';
                if($val['link_type'] == 2) { // 抖音推广
                    $params = 'link_id=' . $val['id'] . '&video_id=' . $val['video_id'] . '&video_detail_id=' . $val['video_detail_id'] . '&type=1&source=link';
                    $val['douyin_link'] = $params;
                }
                // end

                $worksheet->setCellValueByColumnAndRow(1, $line, $val['id']);
                $worksheet->setCellValueByColumnAndRow(2, $line, $val['external_link']);
                $worksheet->setCellValueByColumnAndRow(3, $line, empty($videoData[$val['video_id']]) ? '' : $videoData[$val['video_id']]);
                $worksheet->setCellValueByColumnAndRow(4, $line, empty($mediaData[$val['media_id']]) ? '' : $mediaData[$val['media_id']]);
                $worksheet->setCellValueByColumnAndRow(5, $line, date('Y-m-d H:i:s', $val['created_at']));
                if ($val['is_new_recharge_setting'] == 1) {
                    if ($val['recharge_template_id'] != 0) { // 充值模板
                        $worksheet->setCellValueByColumnAndRow(6, $line, empty($rechargeTemplateData[$val['recharge_template_id']]) ? '' : $rechargeTemplateData[$val['recharge_template_id']]);
                    } else {
                        $worksheet->setCellValueByColumnAndRow(6, $line, '按公共配置');
                    }
                } else {
                    // 新版本
                    if ($val['recharge_template_id'] != 0) { // 充值模板
                        $worksheet->setCellValueByColumnAndRow(6, $line, empty($customRechargeTemplate[$val['recharge_template_id']]) ? '' : $customRechargeTemplate[$val['recharge_template_id']]);
                    } else {
                        $worksheet->setCellValueByColumnAndRow(6, $line, '按公共配置');
                    }
                }

                if ($val['is_new_recharge_setting'] == 1) {
                    if ($val['echo_rule_config_id'] == 0) { // 回传规则配置
                        $worksheet->setCellValueByColumnAndRow(7, $line, '按公共配置');
                    } else if ($val['echo_rule_config_id'] == 1) {
                        $worksheet->setCellValueByColumnAndRow(7, $line, '按自然日');
                    } else {
                        $worksheet->setCellValueByColumnAndRow(7, $line, '仅回传首单');
                    }
                } else {
                    $worksheet->setCellValueByColumnAndRow(7, $line, empty($echoRuleConfig[$val['echo_rule_config_id']]) ? '' : $echoRuleConfig[$val['echo_rule_config_id']]);
                }

                $worksheet->setCellValueByColumnAndRow(8, $line, $val['echo_rate']);
                $worksheet->setCellValueByColumnAndRow(9, $line, $is_open_array[$val['is_open']] ?? '未知');
                if (empty($val['recharge_price'])) { // 累计充值金额
                    $val['recharge_price'] = 0;
                }
                $worksheet->setCellValueByColumnAndRow(10, $line, $val['recharge_price']);
                $worksheet->setCellValueByColumnAndRow(11, $line, empty($val['advertiser_id']) ? '' : ' ' . $val['advertiser_id']);
                $worksheet->setCellValueByColumnAndRow(12, $line, $val['douyin_link']);
            }

            $filename = './推广链接导出' . date("Y-m-d") . '.xlsx';
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
            // $writer->save('C:\Users\000\Downloads\充值流水.xlsx');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
            exit;
        }
    }

    //批量关闭链接
    public function batchCloseLink($userInfo, $params = [])
    {
        $ids = explode(',', $params['link_ids']);
        $list = $this->model->whereIn('id', $ids)->select();
        if(empty($list)) {
            return ['message' => Error::PLEASE_SELECT_UPDATE_LINK];
        }

        foreach($list as $key => $value) {
            $data = [
                'id' => $value['id'],
                'video_id' => $value['video_id'],
                'video_detail_id' => $value['video_detail_id'],
                'is_open' => $value['is_open'],
                'echo_rate' => $value['is_open'],
                'advertiser_id' => $value['advertiser_id'],
                'rebate' => $value['rebate'],
                'link_switch' => 0
            ];
            $this->editLink($data, $userInfo);
        }
        return [];
    }
    // 分销商用推广链接列表
    public function getDistributionLinkList($params)
    {
        $info = $this->responsibilityPersonModel->getInfoByWhere(['token' => $params['token']], 'id');
        if (empty($info)) {
            return ['message' => Error::TOKEN_ERROR];
        }

        $pitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $info['id']], 'id');
        $pitcherIds = array_column($pitcher, 'id');

        if (empty($pitcherIds)) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        // 投手搜索
        if (!empty($params['pitcher_id']) && !in_array($params['pitcher_id'], $pitcherIds)) {
            return ['message' => Error::PITCHER_ID_PARAMATER_ERROR];
        }

        // 时间搜索
        if (!empty($params['start_date']) && empty($params['end_date'])) {
            return ['message' => Error::PLEASE_SELECT_END_DATE];
        }
        if (empty($params['start_date']) && !empty($params['end_date'])) {
            return ['message' => Error::PLEASE_SELECT_START_DATE];
        }
        if (strtotime($params['end_date']) - strtotime($params['start_date']) > 86400) {
            return ['message' => Error::CROSS_DAY_QUERY_NOT_SUPPORTED];
        }
        if (strtotime($params['end_date']) < strtotime($params['start_date'])) {
            return ['message' => Error::END_DATE_IS_LESS_THAN_START_DATE];
        }

        if (!empty($params['start_date']) && !empty($params['end_date'])) {
            $where = [
                ['created_at', '>=', strtotime($params['start_date'])],
                ['created_at', '<', strtotime($params['end_date'])]
            ];
        } else {
            $where = [
                ['created_at', '>=', strtotime(date('Y-m-d'))],
                ['created_at', '<', strtotime(date('Y-m-d')) + 86400]
            ];
        }

        if (!empty($params['pitcher_id'])) {
            $where[] = ['responsibility_person_id', '=', $params['pitcher_id']];
        } else {
            $where[] = ['responsibility_person_id', 'in', $pitcherIds];
        }

        $data = $this->model->getDataByWhere($where, 'id, video_id, remark, responsibility_person_id as pitcher_id, created_at');
        $videoIds = array_column($data, 'video_id');
        $pitcherIds = array_column($data, 'pitcher_id');

        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
        $video = array_column($videoData, 'name', 'id');

        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $pitcherIds], 'id, name');
        $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

        foreach ($data as $key => $value) {
            $data[$key]['video_name'] = empty($video[$value['video_id']]) ? '' : $video[$value['video_id']];
            $data[$key]['pitcher_name'] = empty($responsibilityPerson[$value['pitcher_id']]) ? '' : $responsibilityPerson[$value['pitcher_id']];
            $data[$key]['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
        }

        return $data;
    }

    // 开关链接
    public function switchLink($id)
    {
        $info = $this->model->getInfoByWhere(['id' => $id], 'link_switch');
        $saveData = ['id' => $id];
        if ($info['link_switch'] == 0) {
            $saveData['link_switch'] = 1;
            $saveData['release_start_time'] = time();
        } else {
            $saveData['link_switch'] = 0;
            $saveData['release_end_time'] = time();
        }
        $bool = $this->model->edit($saveData);
        return empty($bool) ? false : true;
    }
}
